-- this file write and read data using a palm db

function read()
 -- open in read mode
 file,NumRegs = io.open("db:/AgesNames", "r+")

 -- define a variable
 returnData = {}

 -- Atention!in DB file, the index begin in 0 (zero) 
 -- but in table, array..the index begin in 1 (one)
 for i=0,NumRegs-1 do
  -- open data from index
  file:openrec(i) -- begin in zero
  -- read this data
  data = file:read("*a")
  temp = bin.unpack("SB",data)

  -- add this data to returning variable
  returnData[i+1] = temp[2].."\t"..temp[1]
 end

 file:close()

 -- if are empty, return this information
 if(returnData == nil) then
  returnData[1] = "No data writed"
 end
 
 return returnData
end

function saveData(e, id, arg)

 -- retrive values from fields
 name = gui.gettext(dataName) 
 age = gui.gettext(dataAge)
 dataToWrite = {name,age}

 -- open for write the data base file
 file = io.open("db:/AgesNames","w")

 -- encode, acording the data tyes
 packed = bin.pack("SB",dataToWrite)
 -- how many size is this data?
 index = file:createrec(string.len(packed))
 -- alloc this size on file
 file:openrec(index)
 -- finaly  write 
 file:write(packed)
 -- and close file
 file:close()

 drawGui()
end


function drawGui()

 gui.destroy()
 screen.clear()

 gui.title("Simple read and write")
 gui.nl()
 gui.label("Name:")
 dataName = gui.field(1,10,20)

 gui.label("Age:");
 dataAge = gui.field(1,3,3)

 gui.control{type="button", text="Add", handler=saveData}

 gui.nl()
 data = read()
 gui.list(10,32,data) 
end

drawGui()
gui.main()
